import cherrypy
import sqlite3
import time

from postmarkup import render_bbcode

import Common

class PrivateMessage(Common.Template):
	# Call the default function with no arguments
	def index(self):
		return self.default()
	index.exposed = True

	# This function handles basically everything.  If no ID is given, it 
	# displays in the inbox and outbox of the user.  If an ID is given, it
	# displays the PM with that ID.  Pretty straightforward.
	def default(self, id = None):	
		cursor = cherrypy.thread_data.db.cursor() 
		
		if self.getLoginPermission() >= 3:				
			yield self.error("You are not logged in", True)	
		# Display the inbox and outbox	
		elif id == None:			
			yield self.header("Private Messages")
			yield self.links()
			yield self.breadcrumbs()
			
			yield "<p align='center'><a href='New'>New Message</a></p>"
			
			# Get all of the Private Messages to the logged in user
			cursor.execute('''
				SELECT PrivateMessage.ID, PrivateMessage.Title, User.ID, User.Username
				FROM PrivateMessage, User
				WHERE PrivateMessage.ToUserID = ? AND 
					PrivateMessage.FromUserID = User.ID
				ORDER BY PrivateMessage.ID DESC
				''', (self.getLoginID(),))
				
			yield "<table width='100%'>"
			yield "<tr valign='top'>"
			yield "<td width='49%'>"
			
			# Display these messages in the sent box
			yield "<h2 align='center'>Inbox</h2>"
			yield "<table width='100%' class='pm_list'>"
			yield "<tr><th class='pm_list'>From</th><th class='pm_list'>Title</th></tr>"
			for ID, Title, UserID, Username in cursor.fetchall():
				yield "<tr>"
				yield "<td width='35%%' class='pm_list'><a href='/User/%s'>%s</a></td>" % (UserID, Username)
				yield "<td class='pm_list'><a href='%s'>%s</a></td>" % (ID, Title)
				yield "</tr>"
			yield "</table>"
			
			yield "</td><td width='2%'>&nbsp;</td><td width='49%'>"
			
			# Get all ofthe private messages from the logged in user
			cursor.execute('''
				SELECT PrivateMessage.ID, PrivateMessage.Title, User.ID, User.Username
				FROM PrivateMessage, User
				WHERE PrivateMessage.FromUserID = ? AND 
					PrivateMessage.ToUserID = User.ID
				ORDER BY PrivateMessage.ID DESC
				''', (self.getLoginID(),))
			
			# Display these messages in the sent box
			yield "<h2 align='center'>Sent Box</h2>"
			yield "<table width='100%' class='pm_list'>"
			yield "<tr><th class='pm_list'>To</th><th class='pm_list'>Title</th></tr>"
			for ID, Title, UserID, Username in cursor.fetchall():
				yield "<tr>"
				yield "<td width='35%%' class='pm_list'><a href='/User/%s'>%s</a></td>" % (UserID, Username)
				yield "<td class='pm_list'><a href='%s'>%s</a></td>" % (ID, Title)
				yield "</tr>"
			yield "</table>"
			
			yield "</td>"
			yield "</tr>"
			yield "</table>"
			
			yield self.footer()
		else:
			# An ID was given, show that PM
			yield self.header("Private Messages")
			yield self.links()
			yield self.breadcrumbs()
			
			# Get the private message, from and to user names
			cursor.execute('''
				SELECT PrivateMessage.ID, PrivateMessage.Title, PrivateMessage.Content, F.ID, F.Username, T.ID, T.Username
				FROM PrivateMessage, User F, User T
				WHERE 
				PrivateMessage.FromUserID = F.ID AND
				PrivateMessage.ToUserID = T.ID AND
				PrivateMessage.ID = ?
				''', (id,))
			
			(ID, Title, Content, FUserID, FUsername, TUserID, TUsername) = cursor.fetchone()
			
			# Display the PM
			yield "<p><b>Title:</b> %s</p>" % Title
			yield "<p><b>To:</b> <a href='/User/%s'>%s</a></p>" % (TUserID, TUsername)
			yield "<p><b>From:</b> <a href='/User/%s'>%s</a></p>" % (FUserID, FUsername)
			yield "<p><b>Content:</b></p>"
			yield "<p>%s</p>" % render_bbcode(Content)
			
			yield self.footer()
			
	default.exposed = True
	
	# This message is how to send a new message.  If any arguments are blank,
	# then the new message form is showed.  If not, the message is sent
	def New(self, touser = "", title = "", content = ""):
		# Get the uid of the user to send to
		toid = self.get_uid(touser)
		
		# Clean surrounding spaces
		title = title.strip()
		content = content.strip()
		
		if self.getLoginPermission() >= 3:				
			yield self.error("You are not logged in", True)			
		elif toid != None and title != "" and content != "":
			cursor = cherrypy.thread_data.db.cursor() 
			
			# Create the PM
			cursor.execute('''
				INSERT INTO PrivateMessage (ID, Title, Content, FromUserID, ToUserID)
				VALUES (NULL, ?, ?, ?, ?)
				''', (title, content, self.getLoginID(), toid,))
			
			cherrypy.thread_data.db.commit()			
			
			# Redirect back to the thread at the PM view
			yield self.redirect("/PrivateMessage")
		else:					
			yield self.header("New Private Message")
			yield self.links()
			yield self.breadcrumbs()
			
			# Show the PM form
			yield "<form method='post' action='/PrivateMessage/New'>"
			yield "To User: <br />"			
			yield "<input class='monospace' type='text' name='touser' size='60' value='%s' /><br />" % touser
			yield "Title: <br />"
			yield "<input class='monospace' type='text' name='title' size='60' value='%s' /><br />" % title
			yield "Content: <br />"
			yield "<textarea class='monospace' name='content' rows='20' cols='80'>%s</textarea><br />" % content
			yield "<input type='submit' value='Send' />"
			yield "</form>"
			
			yield self.footer()
	New.exposed = True	
	
	# Get the userid of the a given usrename
	def get_uid(self, username):
		cursor = cherrypy.thread_data.db.cursor() 
		cursor.execute("SELECT User.ID FROM User WHERE User.Username = ?", (username,))
		result = cursor.fetchone()
		
		if result == None:
			return None
		else:
			return result[0]
